package hydrap2p.library.listening;

import hydrap2p.ServiceLocation;
import hydrap2p.library.LibraryListener;
import hydrap2p.library.LibrarySubscriptionType;

import java.util.LinkedList;
import java.util.List;

import org.apache.thrift.TException;

public class Listener {
	public ServiceLocation location;
	public LibraryListener.Client connection;
	public LibrarySubscriptionType subscription;
	
	public boolean synced;
	public List<ListenerEvent> events;
	
	public Listener()
	{
		synced=false;
		events=new LinkedList<ListenerEvent>();
	}
	
	@Override
	public boolean equals(Object e)
	{
		if (! (e instanceof Listener))
			return false;
		
		Listener other=(Listener)e;
		return location.address.equals(other.location.address) &&
			location.port==other.location.port;
	}
	
	@Override
	public int hashCode()
	{
		return location.address.hashCode()+location.port;
	}
	
	public void execute(ListenerEvent event) throws TException {
		if (!synced)
			events.add(event);
		else
			executeActual(event);
	}
	
	private void executeActual(ListenerEvent event) throws TException {
		if (subscription.metadata && event.type==ListenerEventType.ChangedExtra)
			connection.changedExtra(event.related);
		if (subscription.metadata && event.type==ListenerEventType.ChangedMetadata)
			connection.changedMetadata(event.related);
		if (subscription.downloadProgress && event.type==ListenerEventType.NewPartialProgress)
			connection.newPartialProgress(event.related, event.range);
		if (subscription.downloadProgress && event.type==ListenerEventType.DeletePartialProgress)
			connection.deletePartialProgress(event.related, event.range);
		if (subscription.verifiedProgress && event.type==ListenerEventType.NewVerifiedProgress)
			connection.newVerifiedProgress(event.related, event.range);
		if (subscription.verifiedProgress && event.type==ListenerEventType.DeleteVerifiedProgress)
			connection.deleteVerifiedProgress(event.related, event.range);
		if (subscription.shared && event.type==ListenerEventType.NewSharedItem)
			connection.newSharedItem(event.related);
		if (subscription.shared && event.type==ListenerEventType.RemovedSharedItem)
			connection.removedSharedItem(event.related);
		if (event.type==ListenerEventType.Ping)
			connection.ping();
		
	}

	
}
